import os
import markdown
from typing import Optional
from ..config import OUTPUT_DIR
from ..utils.logger import setup_logger
from deepseek import DeepSeekAPI
import json

logger = setup_logger('process_service')

class ProcessService:
    def __init__(self):
        self.deepseek_api = DeepSeekAPI()
        os.makedirs(OUTPUT_DIR, exist_ok=True)

    def process_text(self, text: str, prompt_type: str, target_language: Optional[str] = None, summary_length: Optional[int] = None) -> str:
        """处理文本"""
        try:
            # 准备请求参数
            request_params = {
                "text": text[:200] + "..." if len(text) > 200 else text,  # 日志中只显示前200个字符
                "prompt_type": prompt_type,
                "target_lang": target_language,
                "summary_length": summary_length
            }
            logger.info(f"准备调用大模型API，请求参数: {json.dumps(request_params, ensure_ascii=False, indent=2)}")
            
            # 调用DeepSeek API处理文本
            result = self.deepseek_api.process(
                text=text,
                prompt_type=prompt_type,
                target_lang=target_language,
                summary_length=summary_length
            )
            
            # 记录响应结果（如果结果太长，只记录部分）
            response_preview = result[:500] + "..." if len(result) > 500 else result
            logger.info(f"大模型API调用成功，响应结果预览: {response_preview}")
            
            return result
            
        except Exception as e:
            logger.error(f"调用大模型API失败: {str(e)}", exc_info=True)
            raise

    def save_result(self, text: str, filename: str, temp_dir: str) -> str:
        """保存处理结果"""
        try:
            # 生成输出文件名
            output_filename = f"{os.path.splitext(filename)[0]}_processed.md"
            output_path = os.path.join(temp_dir, "output", output_filename)
            
            # 确保输出目录存在
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            
            # 保存处理结果
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(text)
            
            logger.info(f"处理结果已保存到文件: {output_path}")
            return output_filename
            
        except Exception as e:
            logger.error(f"保存处理结果失败: {str(e)}", exc_info=True)
            raise

    def get_markdown(self, text: str) -> str:
        """将文本转换为Markdown格式"""
        try:
            return markdown.markdown(text)
        except Exception as e:
            logger.error(f"Markdown转换失败: {str(e)}", exc_info=True)
            raise 